package com.flink.datastreamapi.transformation;


import com.flink.datastreamapi.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class TransFlatMap {

    //**需求**：如果输入的数据是sensor_1，只打印vc；如果输入的数据是sensor_2，既打印ts又打印vc
    public static void main(String[] args) throws Exception {

        //获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置并行度为1
        env.setParallelism(1);

        //数据源
        DataStreamSource<WaterSensor> dataStreamSource = env.fromElements(
                new WaterSensor("sensor_1", 1l, 1),
                new WaterSensor("sensor_2", 2l, 2),
                new WaterSensor("sensor_2", 2l, 2),
                new WaterSensor("sensor_3", 3l, 3));
        //数据转换
        SingleOutputStreamOperator<String> flatMap = dataStreamSource.flatMap(new CustomFlatMap());
        //输出
        flatMap.print();
        //执行
        env.execute();

    }

    public static class CustomFlatMap implements FlatMapFunction<WaterSensor,String> {

        @Override
        public void flatMap(WaterSensor value, Collector<String> out) throws Exception {
            //如果输入的数据是sensor_1，只打印vc；如果输入的数据是sensor_2，既打印ts又打印vc
            switch (value.id){
                case "sensor_1":
                    out.collect(String.valueOf(value.vc));
                    break;
                case "sensor_2":
                    out.collect(String.valueOf(value.vc));
                    out.collect(String.valueOf(value.ts));
                    break;
                default:
                    break;
            }

        }
    }
}
